<template>
  <div>
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model.trim="formData.projectName"></el-input>
      </el-form-item>
      <el-form-item label="项目编号" prop="projectCode">
        <el-input v-model.trim="formData.projectCode"></el-input>
      </el-form-item>
      <el-form-item label="项目负责人" prop="projectLeaderId">
        <!-- <el-select-v2
          v-model="formData.projectLeaderId"
          filterable
          :options="userList"
          placeholder="请选择人员"
          style="width: 215px"
        >
        </el-select-v2>-->
        <el-select
          v-model="formData.projectLeaderId"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData"
        >
          <!-- reserve-keyword -->
          <!-- :loading="loading" -->
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型" prop="projectTypeList">
        <el-select
          v-model="formData.projectTypeList"
          multiple
          value-key="projectCode"
        >
          <el-option
            id="default-option"
            v-for="item in typeList"
            :key="item.projectCode"
            :label="item.projectName"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目成员" prop="projectUserList">
        <el-select
          ref="selectRef"
          v-model="formData.projectUserList"
          filterable
          remote
          multiple
          placeholder="请输入姓名"
          :remote-method="getTeamUserData"
          value-key="userId"
        >
          <!-- :loading="loading" -->
          <el-option
            v-for="item in teamList"
            :key="item.userId"
            :label="item.label"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-row justify="end">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, ref, defineProps, onMounted, toRef } from "vue";
import { getUserList, postUserInfo } from "/@/api/user";
import { postAddProject, postProjectManageUpdate } from "/@/api/project";
// import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { cloneDeep } from "lodash-es";

// const router = useRouter();
// const route = useRoute();
const formRef = ref<HTMLFormElement | null>(null) as any;
const selectRef = ref<HTMLElement | null>(null) as any;
const emit = defineEmits([
  "update:dialogVisible",
  "resetGetData",
  "resetVisible"
]);
const props = defineProps({
  nodeId: {
    type: Number,
    default: 0
  },
  cacheParentCode: {
    type: String,
    default: ""
  },
  projectInfo: {
    type: Object,
    default: () => {}
  },
  mode: {
    type: String,
    default: "add"
  }
});

let formData = reactive({
  projectName: "",
  projectCode: null,
  projectLeaderId: null,
  projectTypeList: [],
  projectUserList: []
});

let userList = ref([]);
let teamList = ref([]);

const currentInfo = toRef(props, "projectInfo");

const typeList = [
  {
    projectCode: 1,
    projectName: "默认类型"
  }
  // {
  //   projectCode: 2,
  //   projectName: "项目类型2"
  // }
];

const formRules = {
  projectName: {
    required: true,
    message: "请输入项目名称",
    trigger: "change"
  },
  projectCode: {
    required: true,
    message: "请输入项目编号",
    trigger: "change"
  },
  projectLeaderId: {
    required: true,
    message: "请选择项目负责人",
    trigger: "change"
  },
  projectTypeList: {
    required: true,
    message: "请输入项目类型",
    trigger: "change"
  }
};

async function getTableData(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return { value: item.id, label: `${item.name}(${item.userName})` };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

const getTeamUserData = async (query = "") => {
  if (!query) {
    teamList.value = [];
    return;
  }

  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      teamList.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: `${item.name}`,
          label: `${item.name}(${item.userName})`
        };
      });

      // // 问题未复现,待确认
      // teamList.value = data.list
      //   .map(item => {
      //     return {
      //       userId: item.id,
      //       userName: item.name,
      //       label: `${item.name}(${item.userName})`
      //     };
      //   })
      //   .concat(formData.projectUserList);

      // // 去重处理

      // let obj = {};
      // teamList.value = teamList.value.reduce(function (item, next) {
      //   obj[next.userId] ? "" : (obj[next.userId] = true && item.push(next));
      //   return item;
      // }, []);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSubmit = async () => {
  try {
    const isValid = await new Promise(resolve =>
      formRef.value.validate(resolve)
    );
    if (!isValid) return;

    let params = JSON.parse(
      JSON.stringify(Object.assign(formData, { parentId: props.nodeId }))
    );
    if (props.mode === "edit") {
      params = Object.assign(params, { id: currentInfo.value.id });
    }
    params.projectUserList &&
      params.projectUserList.length &&
      params.projectUserList.forEach(item => {
        delete item.label;
      });

    if (props.mode === "edit") {
      delete params.parentId;
      console.log(params, "submit");
      const { code } = await postProjectManageUpdate(params);
      if (code === 200) {
        NotifMessage.success("修改成功");
        resetTableData();
      }
    } else {
      const { code } = await postAddProject(params);
      if (code === 200) {
        NotifMessage.success("添加成功");
        resetTableData();
      }
    }
  } catch (err) {
    console.log(err);
  }
};

// 关闭弹框并更新数据
const resetTableData = () => {
  emit("update:dialogVisible", false);
  emit("resetGetData");
  emit("resetVisible");
};

const handleCancel = () => {
  emit("update:dialogVisible", false);
  emit("resetVisible");
};

// 请求数据需再处理
onMounted(async () => {
  if (props.mode === "edit") {
    const copyCurrentInfo = cloneDeep(currentInfo.value);
    formData.projectName = copyCurrentInfo.projectName;
    formData.projectCode = copyCurrentInfo.projectCode;
    formData.projectLeaderId = Number(copyCurrentInfo.projectLeaderId);

    const res = await searchUserName([formData.projectLeaderId]);
    userList.value = res;
    formData.projectTypeList = copyCurrentInfo?.projectTypeList.map(item => {
      return {
        projectCode: Number(item.projectCode),
        projectName: item.projectName
      };
    });
    // 项目成员处理

    const projectUsers = copyCurrentInfo.projectUserList.map(item => {
      return item.userId;
    });

    const resUserList = await searchTeamUserName(projectUsers);
    formData.projectUserList = resUserList || [];
    teamList.value = formData.projectUserList;
  } else {
    if (props.nodeId) {
      formData.projectCode = props.cacheParentCode;
    }
  }
  // selectRef.value.modelValue.push({
  //   userId: 28,
  //   userName: "lucuxx",
  //   label: "lucuxx(lucux)"
  // });
  // // formData.projectUserList.push({
  // //   userId: 28,
  // //   userName: "lucuxx",
  // //   label: "lucuxx(lucux)"
  // // });
  // selectRef.value.selectOption = [
  //   {
  //     userId: 28,
  //     userName: "lucuxx",
  //     label: "lucuxx(lucux)"
  //   }
  // ];

  // selectRef.value.selected.push({
  //   value: Proxy,
  //   currentLabel: "lucuxx(lucux)",
  //   hitState: false
  // });
  console.log(selectRef.value, "selectRef");
});

// 根据id 查询用户名
const searchUserName = async userList => {
  if (!userList.length) return;
  let promises = userList.map(user => {
    return postUserInfo({ id: user });
  });
  let results = await Promise.all(promises);
  // console.log(results, "results");
  const users = results.map(item => {
    return {
      value: (item as any)?.data.id,
      label: `${(item as any)?.data.name}(${(item as any)?.data.userName})`
    };
  });

  return users;
};

// 根据id 查询团队成员的名称
const searchTeamUserName = async userList => {
  if (!userList.length) return;
  let promises = userList.map(user => {
    return postUserInfo({ id: user });
  });
  let results = await Promise.all(promises);
  // console.log(results, "results");
  const users = results.map(item => {
    return {
      userId: (item as any)?.data.id,
      userName: `${(item as any)?.data.name}`,
      label: `${(item as any)?.data.name}(${(item as any)?.data.userName})`
    };
  });

  return users;
};

// 初始化用户下拉数据
async function initUserData() {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: ""
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return { value: item.id, label: `${item.name}(${item.userName})` };
      });
      teamList.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: `${item.name}`,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

initUserData();
</script>
